<template>
  <div class='app-container'>
    <div class='app-box clear'>
        <div class='inputbox'>
           
            <div class="day-top clearfix">
              <div class="top">
                <span>出单时间：</span>
              
                  <!-- {{time1}} -->
                  <el-date-picker
                    v-model="time1"
                    type="daterange"
                    range-separator="至"
                    size="mini"
                    clearable
                    prefix-icon=''
                    
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
              </div>
              <div class="top3">
                <span>所属机构：</span>
                <!-- <ztree-select class="wd210" v-model="organizationUnitId" :treedata="treeData" :childprops="childprops" @change='setSelectedId'></ztree-select> -->
                <el-select v-model="organizationUnitId" placeholder="请选择" size="mini" style="width:175px;" multiple collapse-tags>
                  <el-option
                    v-for="item in treeData"
                    :key="item.organizationId"
                    :label="item.organizationName"
                    :value="item.organizationId">
                  </el-option>
                </el-select>
              </div>
               <div class="top2">
                <span>保险公司：</span>
                 <el-select  class="wd130" size="mini" v-model="Insurance" placeholder="请选择保险公司" >
                  <el-option-group v-for="group in companies" :key="group.letter" :label="group.letter">
                    <el-option v-for="item in group.insurances" :key="item.id" :label="item.insuranceName" :value="item.id">
                    </el-option>
                  </el-option-group>
                </el-select>
              </div>
                <!-- <div class="top2">
                <span>数据类型：</span>
            
                   <el-select v-model="value5" size="mini" class="wd130"  placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </div> -->
              <el-dropdown split-button type="primary" @click="toSearch" size="mini" style="height:29px;" placement='bottom-end' class="day-dropdown"  @command='exportForm'>
                查询
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item style="width:87px; text-align:center;">导出</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <!-- <div class="unitbox"><span>(单位：万元)</span></div> -->
            <div class="cenVal">
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  {{allSelect}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                 <el-dropdown-item command="1">保单量</el-dropdown-item>
                  <el-dropdown-item command="2">总保费（万元）</el-dropdown-item>
                  <el-dropdown-item command="3">净保费（万元）</el-dropdown-item>
                  <el-dropdown-item command="4">总收入（万元）</el-dropdown-item>
                  <el-dropdown-item command="5">总支出（万元）</el-dropdown-item>
                  <el-dropdown-item command="6">利润（万元）</el-dropdown-item>
                  <el-dropdown-item command="7">利润率（百分比）</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
             <!-- 列表 -->
            <div class="pday-table daySty">
              <el-table
                class="reportTd"
                :data="tableData3"
                header-align="left"
                align="right"
                 stripe
                v-loading="loading"
                style="width: 100%">
                <el-table-column
                  fixed
                  prop="insuranceName"
                  align="center"
                  :render-header="renderHeader"
                  width="130" >
                   <template slot-scope="scope">
                     
                     <span @click="toDayForm(scope.row.id,time1)" style="cursor:pointer;" class="ishover">{{scope.row.displayName}}</span>
                   </template>
                </el-table-column>
         
                <el-table-column 
                 align="right"
                  v-for="(col,index) in columns"
                  :key="col.week"
                  :prop="col.week" 
                  :label="col.date+col.week"
                  min-width="105px">
                   <template slot-scope="scope">
                      <div :ref="'alltd'+col.date+col.week | format">
                      <el-popover trigger="click" class="item"  placement="bottom" >
                        <div  class='compony_text'>
                           <div class="baofe1">
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">保单量:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].guaranteeSlipCount}}</div>
                            </div>
                          </div>
                          <div class="baofe1">
                            <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">总保费:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].totalPremium | keepTwoNum}}</div>
                            </div>
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">净保费:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].totalNetPremium | keepTwoNum}}</div>
                            </div>
                          </div>
                          <div class="baofe1">
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">总收入:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].incomes | keepTwoNum}}</div>
                            </div>
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">总支出:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].expends | keepTwoNum}}</div>
                            </div>
                          </div>
                          <div class="baofe1">
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">利润:</div>
                              <div class="wd120" style="text-align:left">{{scope.row.values[index].profit | keepTwoNum}}</div>
                            </div>
                             <div class="baofeiDetail">
                              <div class="wd70" style="text-align:right">百分比:</div>
                              <div class="wd120" style="text-align:left">{{((scope.row.values[index].profitRate*100).toFixed(2))}}%</div>
                            </div>
                          </div>
                          <!-- <div class="baofe1" style="text-align:center;">
                             <a @click="toDayForm(scope.row.insuranceId,col)">查看更多</a>
                          </div> -->
                        </div>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 1 && scope.row.values[index].guaranteeSlipCount != null">{{scope.row.values[index].guaranteeSlipCount}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 2 && scope.row.values[index].totalPremium != null">{{scope.row.values[index].totalPremium | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 3 && scope.row.values[index].totalNetPremium != null">{{scope.row.values[index].totalNetPremium | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 4 && scope.row.values[index].incomes != null">{{scope.row.values[index].incomes | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 5 && scope.row.values[index].expends != null">{{scope.row.values[index].expends | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 6 && scope.row.values[index].profit != null">{{scope.row.values[index].profit | keepTwoNum}}</span>
                          <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 7 && scope.row.values[index].profitRate != null" >{{((scope.row.values[index].profitRate*100).toFixed(2))}}%</span>
                       </el-popover>
                       <span v-if="value5 == 1 && scope.row.values[index].guaranteeSlipCount == null">-</span>
                        <span v-if="value5 == 2 && scope.row.values[index].totalPremium == null" >-</span>
                       <span v-if="value5 == 3 && scope.row.values[index].totalNetPremium == null">-</span>
                       <span v-if="value5 == 4 && scope.row.values[index].incomes == null">-</span>
                       <span v-if="value5 == 5 && scope.row.values[index].expends == null">-</span>
                       <span v-if="value5 == 6 && scope.row.values[index].profit == null">-</span>
                       <span v-if="value5 == 7 && scope.row.values[index].profitRate == null">-</span>
                        <!-- <span class="companytest"></span> -->
                    </div>
                  </template>
                   </el-table-column>
                </el-table-column>
                       <el-table-column
                  prop="total"
                  align="center"
                  label="合计"
                  fixed="right"
                 >
                   <template slot-scope="scope">
                      <el-popover trigger="click" class="item"  placement="bottom" >
                       <div  class='compony_text' v-if="scope.row.total != null">
                         <div class="baofe1">
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right">保单量:</div>
                                  <div class="wd120" style="text-align:left">{{scope.row.total.guaranteeSlipCount}}</div>
                                </div>
                              </div>
                            <div class="baofe1">
                              <div class="baofeiDetail">
                                <div class="wd70" style="text-align:right;">总保费:</div>
                                <div class="wd120" style="text-align:left;">{{scope.row.total.totalPremium | keepTwoNum}}</div>
                              </div>
                              <div class="baofeiDetail">
                                <div class="wd70" style="text-align:right;">净保费:</div>
                                <div class="wd120" style="text-align:left;">{{scope.row.total.totalNetPremium | keepTwoNum}}</div>
                              </div>
                            </div>
                             <div class="baofe1">
                               <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right;">总收入:</div>
                                  <div class="wd120" style="text-align:left;">{{scope.row.total.incomes | keepTwoNum}}</div>
                                </div>
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right;">总支出:</div>
                                  <div class="wd120" style="text-align:left;">{{scope.row.total.expends | keepTwoNum}}</div>
                                </div>
                             </div>
                             <div class="baofe1">
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right">利润:</div>
                                  <div class="wd120" style="text-align:left">{{scope.row.total.profit | keepTwoNum}}</div>
                                </div>
                                <div class="baofeiDetail">
                                  <div class="wd70" style="text-align:right">百分比:</div>
                                  <div class="wd120" style="text-align:left">{{((scope.row.total.profitRate*100).toFixed(2))}}%</div>
                                </div>
                             </div>
                              <div class="baofe1" style="text-align:center;overflow:hidden;">
                                <a  @click="toDayForm(scope.row.id,time1)">查看更多</a>
                              </div>
                        </div>
                        <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 1 && scope.row.total.guaranteeSlipCount !=null">{{scope.row.total.guaranteeSlipCount}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 2 && scope.row.total.totalPremium !=null">{{scope.row.total.totalPremium | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 3 && scope.row.total.totalNetPremium !=null">{{scope.row.total.totalNetPremium | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 4 && scope.row.total.incomes !=null">{{scope.row.total.incomes | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 5 && scope.row.total.expends !=null">{{scope.row.total.expends | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 6 && scope.row.total.profit !=null">{{scope.row.total.profit | keepTwoNum}}</span>
                           <span style=" cursor: pointer" slot="reference" class="ptab-span" v-if="value5 == 7 && scope.row.total.profitRate !=null">{{((scope.row.total.profitRate*100).toFixed(2))}}%</span>
                        
                          <!-- {{scope.row.total}} -->
                       </el-popover>
                        <!-- <span class="companytest"></span> -->
                         <span v-if="value5 == 1 && scope.row.total.guaranteeSlipCount == null">-</span>
                        <span v-if="value5 == 2 && scope.row.total.totalPremium == null">-</span>
                       <span v-if="value5 == 3 && scope.row.total.totalNetPremium == null">-</span>
                       <span v-if="value5 == 4 && scope.row.total.incomes == null">-</span>
                       <span v-if="value5 == 5 && scope.row.total.expends == null">-</span>
                       <span v-if="value5 == 6 && scope.row.total.profit == null" >-</span>
                       <span v-if="value5 == 7 && scope.row.total.profitRate== null">-</span>
                  </template>
                </el-table-column>
              </el-table>
            </div> 
        </div>
    </div>
</div>
</template>
<script>
import ztreeSelect from "@/components/z-select/index.vue";
export default {
  components: {
    ztreeSelect
  },
  filters:{
    keepTwoNum:function(val){
      val = Number(val)
      return val.toFixed(2)
    },
    	format: function(val) {
      val = val.replace('星期日','sunday')
      return val;
    }
  },
  data() {
    return {
      time1:'',
      companies:{},
      treeData: [],
      loading: false,
      //数组子级相关参数
      childprops: {
        name: "displayName", //显示名字
        children: "organizationUnits", //子级字段名
        lv: "level" //当前层级
      },
      organizationUnitId: '',
      type1: "0",

      //保险公司选项
      companies: [],
      Insurance: '',

      //数据类型选项
       allSelect:'总保费',
     options: [
        {
          value: "1",
          label: "保单量"
        },
        {
          value: "2",
          label: "总保费"
        },
        {
          value: "3",
          label: "净保费"
        },
        {
          value: "4",
          label: "总收入"
        },
        {
          value: "5",
          label: "总支出"
        },
        {
          value: "6",
          label: "利润"
        },
        {
          value: "7",
          label: "利润率"
        }
      ],
      value5: '2',

      //列表数据
      tableData3: [],
    
      //表头列表
     columns: [],
      //列表合计详情

    };
  },
  mounted() {
    
    this.getCompanies();
    this.getUnits();
    if(this.$route.query.beginDate || this.$route.query.endDate){
      let arrR = [this.$route.query.beginDate,this.$route.query.endDate]
      this.time1 = arrR
         console.log(this.time1)
      if(this.$route.query.insuranceId){//Insurance
        this.Insurance = this.$route.query.insuranceId;
        console.log(this.Insurance)
      }
      if(this.$route.query.organizationIds && typeof(this.$route.query.organizationIds) == "string"){//organizationId
         console.log(1)
          let arr = []
        //  console.log()
        //  this.$route.query.organizationIds =Number(this.$route.query.organizationIds)
         arr.push(Number(this.$route.query.organizationIds))
          this.organizationUnitId = arr
      }else{
        console.log(2)

        for(let i = 0 ;i<this.$route.query.organizationIds.length;i++ ){
          this.$route.query.organizationIds[i] = Number(this.$route.query.organizationIds[i])
        }
        this.organizationUnitId = this.$route.query.organizationIds;
      }
      // this.value5 = this.$route.query.queryData;
    }else{
       this.getTime();
    }
    
    this.getFirstData();
    // console.log(this.time1[0])
  },
  watch: {
    $route(to, from) {
      console.log('the route is change')
      let arrR = [this.$route.query.beginDate,this.$route.query.endDate]
      this.time1 = arrR
         console.log(this.time1)
      if(this.$route.query.insuranceId){//Insurance
        this.Insurance = this.$route.query.insuranceId;
        console.log(this.Insurance)
      }
      if(this.$route.query.organizationIds){//organizationId
        this.organizationUnitId = this.$route.query.organizationIds;
      }
      // this.value5 = this.$route.query.queryData;
      this.getFirstData();
    }
  },
  computed: {},
  created() {},
  methods: {
    	geshiTable(){
        let that = this
        setTimeout(function(){
          //  console.log(that.$refs)
          let tdObj = that.$refs
					console.log("tdobj-----------")
					console.log(tdObj)
          for(let k in tdObj){
            if(k.substring(15,) == 'sunday'){
              let aa=tdObj[k]
              for(let i=0; i<aa.length; i++){
                // console.log(aa[i])
                aa[i].parentNode.parentNode.style.borderRight='1px solid #aeaeae'
              }
            }
          }
        },10)
    },
      handleCommand(command) {
       this.value5 = command
       this.allSelect = this.options[command-1].label
      },
     renderHeader(h, { column, $index }){
      return (
        <div class="thHead">
            <span style="left:56px;">&nbsp;&nbsp;月份&nbsp;&nbsp;</span>
            <span style="left:-15px;">组织机构</span>
        </div>
      )
    },
       // 公司
    getCompanies() {
      let that = this
      let all = {
        letter: "",
        insurances: [{ insuranceName: "全部保险公司", id: "" }]
      };
      let params = {}
      this.post(params, 'services/app/common/GetGroupInsurances').then(rs => {
        console.log(rs)
        if (rs.success) {
          let result = rs.result.items;
          result.unshift(all);
          that.companies = result;
        }
      })
    },
    //获取列表数据
     getFirstData(){
      //  console.log(this.time1)
      this.loading = true;
      let params= {
        beginDate:this.time1[0],
        endDate :this.time1[1],
        organizationIds :this.organizationUnitId,
        insuranceId :this.Insurance,
        queryData : this.value5
      }
      this.post(params,'services/app/report/Organization_Days').then(rs => {
        if(rs.success){
          this.loading = false;
          this.geshiTable()
          // this.tableData3 = rs.result.item;
          this.columns = rs.result.columns;
          if(rs.result.item.length < 6){
						let values = []
						for(let i = 0;i<this.columns.length;i++){
									values.push({
                    totalPremium: null, 
                    totalNetPremium: null, 
                    incomes: null, 
                    expends: null, 
                    profit: null,
                    profitRate:null
									},)
							
						}
            let bbVal = []
             for(let j = 0; j <rs.result.item.length; j++){
              bbVal.push(rs.result.item[j])
            }
						for(let k = 0; k< 6-rs.result.item.length; k++){
              let total={
                totalPremium: null, 
                totalNetPremium: null, 
                incomes: null, 
                expends: null, 
                profit: null,
                profitRate:null
                }

              bbVal.push({
                total:total,
                values:values
                })
            }
            // bbVal.push(rs.result.item)
						this.tableData3 = bbVal;
          }else{
            this.tableData3 = rs.result.item;
          }
        }else{
        		this.loading = false;
        			this.$notify.error({
		            title: "错误",
		            message: rs.error.message
		          });
        	}
      })
    },
    // 机构
     getUnits() {
      let params = {};
      this.post(params, "services/app/common/ChildOrganizations").then(rs => {
        console.log(rs);
        if (rs.success) {
          this.treeData = rs.result;
        }
      });
    },
    setSelectedId(val) {
      this.organizationUnitId = val;
    },
     // 格式化
    formatDate(time){
        var date = new Date(time);

        var year = date.getFullYear(),
            month = date.getMonth()+1,//月份是从0开始的
            day = date.getDate(),
            hour = date.getHours(),
            min = date.getMinutes(),
            sec = date.getSeconds();
        var newTime = year + '-' +
                    (month < 10? '0' + month : month) + '-' +
                    (day < 10? '0' + day : day) + ' ' +
                    (hour < 10? '0' + hour : hour) + ':' +
                    (min < 10? '0' + min : min) + ':' +
                    (sec < 10? '0' + sec : sec);
        return newTime;         
    },
     //跳转到日报表
     toDayForm(id,date){
      //  console.log(ins)
      //  date = date.slice(0,-1);
      //  console.log(date);
      //  var T = new Date();
      //  var year = T.getFullYear();
      //  var time = year+'-'+date;
      // console.log(date[1].substring(0,7))
      // return
       this.$router.push({name:'dayform',
       query:{startDay:this.time1[0],endDay:this.time1[1],org:id}});
    },
    //获取列表数据
    getList() {
     
      let params = {
          "beginDate":this.time1[0],
          "endDate":this.time1[1],
          "organizationId": organizationUnitId,
          "insuranceId": "",
          "queryData": 1
      };
      this.post(params, "services/app/common/GetOrganizationUnits").then(rs => {
        console.log(rs);
        if (rs.success) {
          let data = rs.result;
          let arr = [];
          arr.push(data);
          this.treeData = rs.result;
        }
      });
    },
    //获取时间
    getTime(){

      var arr = []
      // var endDay = this.getNowFormatDate(0).substring(8,10)
      // var yesDay = Number(endDay-1)
      // if(yesDay<10){
      //   var yesDay = '0'+yesDay
      // }
      // if(endDay != "01"){
      //   arr[0] =this.getNowFormatDate(0).substring(0,8) + '01';
      //   arr[1] = this.getNowFormatDate(0).substring(0,8)+yesDay //ok
      // }else{
        arr[0] = this.getNowFormatDate(0).substring(0,8) + '01';
        arr[1] = this.getNowFormatDate(0).substring(0,8)+this.mGetDate(0) //ok
      // }    
      this.time1 = arr
    },
      //获取当前时间，格式YYYY-MM-DD
     getNowFormatDate(mon) {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1 - mon;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    },
    //获取当前月份天数
    mGetDate(mon){
     var date = new Date();
     var year = date.getFullYear();
     var month = date.getMonth()+1-mon;
     var d = new Date(year, month, 0);
     return d.getDate();
    },
    //搜索
     toSearch(){
       	 if(this.time1 != null){
          this.$router.push({
            name:'zdayform',
            query:{
              beginDate:this.time1[0],
              endDate :this.time1[1],
              organizationIds :this.organizationUnitId,
              insuranceId :this.Insurance,
              queryData : this.value5,
              time:new Date().getTime()
            }
          })
        }else{
          this.$message.error('请输入出单时间');
        }
    },
    //导出
    exportForm(){
      let params= {
        beginDate:this.time1[0],
          endDate :this.time1[1],
          organizationIds :this.organizationUnitId,
          insuranceId :this.Insurance,
          queryData : this.value5,
      }
      this.post(params,'services/app/report/Organization_Days_Export').then(rs => {
        if(rs.success){
          let filePath=rs.result.filePath
          console.log(filePath)
          window.location.href=filePath
        }else{
        		this.loading = false;
        			this.$notify.error({
		            title: "错误",
		            message: rs.error.message
		          });
        	}
      })
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss"  scoped>
.ishover:hover{
  // color:red;
  font-weight: 600;
  border-bottom: 1px dotted #333;
}
.wd60 {
  width: 60px;
}
.wd70 {
  width: 70px;
}
.wd90 {
  width: 90px;
}
.wd120 {
  width: 120px;
}
.wd130 {
  width: 130px;
}
.wd210 {
  width: 160px;
}
.wd230 {
  width: 230px;
}
.el-table th, .el-table tr{
  background: red !important;
}
.app-box {
  color: #333;
  .day-top{
    margin-bottom: 30px;
    color: #666;
    .top {
      float: left;
      width:300px;
       margin-right: 20px;
    }
    .top_1 {
      width: 32%;
    }
    .top1 {
      float: left;
      width: 230px;
      margin-right: 20px;
    }
     .top2 {
      float: left;
      width: 240px;
      margin-right: 20px;
    }
     .top3 {
      float: left;
      width: 250px;
       margin-right: 20px;
    }
    .day-dropdown {
      float: right;
      
    }
  }
  .unitbox {
    height: 40px;
    line-height: 40px;
    span {
      font-weight: 600;
    }
  }
}
.baofe1{
  width:400px;
.baofeiDetail{
  width: 49%;
  display: inline-block;
    div{
      padding: 8px;
      display: inline-block;
    }
  }
  a{
    display: block;
    width: 100%;
    color: #027dca;
    font-size: 13px;
    margin-top: 5px;
  }
  a:hover{
    text-decoration: underline
  }
}
@media screen and (min-width: 1280px) and (max-width: 1380px) {
  .wd210 {
    width: 130px;
  }
  .wd230 {
    width: 220px;
  }
  .app-box {
    .day-top {
       margin-bottom: 30px;
      .top {
        float: left;
        width: 30%;
      }
      .top1 {
        float: left;
        width: 19%;
      }
    }
  }
}
</style>